package com.dzl.exchange;

import com.alibaba.fastjson.JSONObject;
import com.dzl.base.controller.BaseController;
import com.dzl.exchange.pojo.WelfareExchange;
import com.dzl.exchange.pojo.dto.ExchangeGoodsSkuDto;
import com.dzl.exchange.pojo.dto.ExchangeMealGoodsDto;
import com.dzl.exchange.pojo.dto.MealGoodsSkuListDto;
import com.dzl.exchange.pojo.query.ExchangeGroupQuery;
import com.dzl.exchange.pojo.vo.ExchangeGroupVo;
import com.dzl.exchange.pojo.vo.ExchangeMealGoodsVo;
import com.dzl.exchange.pojo.vo.ExchangeSkuGoodsVo;
import com.dzl.exchange.service.WelfareExchangeGoodsService;
import com.dzl.exchange.service.WelfareExchangeService;
import com.dzl.goods.pojo.query.WelfareGoodsManageQuery;
import com.dzl.util.EmptyUtils;
import com.dzl.util.JsonResult;
import com.dzl.util.PageUtils;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 兑换券组表(WelfareExchangeSecretGroup)表控制层
 * @author caobucao
 * @date 2021-07-09 17:24:46
 */
@RestController
@RequestMapping("/welfareExchange")
public class WelfareExchangeController extends BaseController {

    @Autowired
    private WelfareExchangeService service;
    @Autowired
    private WelfareExchangeGoodsService welfareExchangeGoodsService;
    @Autowired
    private WelfareExchangeService welfareExchangeService;

    /**
     * 分页查询兑换券组列表
     * @date 2021/7/9 17:35
     * @author caobucao
     * @param query 查询条件
     * @return com.dzl.util.PageUtils<com.dzl.exchangesecretgroup.pojo.vo.ExchangeGroupVo>
     */
    @GetMapping("/queryExchangeGroupVoListPage")
    public PageUtils<ExchangeGroupVo> queryExchangeGroupVoListPage(ExchangeGroupQuery query) {
        PageInfo<ExchangeGroupVo> pageInfo = service.selectExchangeGroupVoListPage(query);
        return new PageUtils<>(pageInfo);
    }

    /**
     * 通过id获取兑换券信息
     * @date 2021/7/13 12:03
     * @author caobucao
     * @param id 兑换券id
     * @return com.dzl.util.JsonResult<com.dzl.exchange.pojo.WelfareExchange>
     */
    @GetMapping("/getExchangeInfo")
    public JsonResult<WelfareExchange> getExchangeInfo(Integer id) {
        return JsonResult.success(service.selectByPrimaryKey(id));
    }

    /**
     * 保存兑换券---添加兑换券，生成
     * @date 2021/7/9 19:23
     * @author caobucao
     * @param group 兑换券组对象
     * @return com.dzl.util.JsonResult<java.lang.String>
     */
    @PostMapping("/saveExchangeGroup")
    public JsonResult<String> saveExchangeGroup(@RequestBody WelfareExchange group) {
        if(EmptyUtils.isEmpty(group.getName())) {
            return JsonResult.paramErrWithMsg("请输入兑换券名称");
        }
        if(EmptyUtils.isEmpty(group.getQuantity())) {
            return JsonResult.paramErrWithMsg("请输入兑换券券密数量");
        }else{
            if(group.getQuantity()>1000){
                return JsonResult.paramErrWithMsg("兑换券密数量限制1000张");
            }
        }
        if(EmptyUtils.isEmpty(group.getId())) {
            group.setCreater(getAdminInfo().getId());
            group.setCreater(getAdminInfo().getId());
            group.setUpdaterName(getAdminInfo().getUserName());
            group.setCreaterName(getAdminInfo().getUserName());
            group.setCreateTime(new Date());
            group.setUpdateTime(new Date());
        } else {
            return JsonResult.paramErrWithMsg("不允许修改兑换券");
        }
        Integer count = service.saveExchangeGroup(group);
        return count > 0 ? JsonResult.success("新增成功，共新增："+count+"条兑换券") : JsonResult.paramErrWithMsg("保存失败！");
    }

    /**
     * 获取兑换券选商品规则下的选中的SKU及商品--- 分页
     * @date 2021/7/13 20:00
     * @author caobucao
     * @param exchangeGroupId 查找参数
     * @return com.dzl.util.PageUtils<com.dzl.goods.pojo.vo.WelfareGoodsManageVo>
     */
    @GetMapping("/getExchangeSkuAndGoods")
    public JsonResult<Map> getExchangeSkuAndGoods(Integer exchangeGroupId) {
        Map result = Maps.newHashMapWithExpectedSize(3);
        if (EmptyUtils.isEmpty(exchangeGroupId)) {
            return null;
        }
        /*if (EmptyUtils.isEmpty(query.getRuleType())) {
            return null;
        }*/
        List<ExchangeSkuGoodsVo> voList = service.getExchangeSkuAndGoods(exchangeGroupId);
        BigDecimal totalDisplayPrice = BigDecimal.ZERO;
        BigDecimal totalCostPrice = BigDecimal.ZERO;
        if(EmptyUtils.isNotEmpty(voList)){
            for (ExchangeSkuGoodsVo exchangeSkuGoodsVo:voList) {
                totalDisplayPrice = totalDisplayPrice.add(exchangeSkuGoodsVo.getDisplayPrice());
                totalCostPrice = totalCostPrice.add(exchangeSkuGoodsVo.getCostPrice());
            }
        }
        result.put("goodsList", voList);
        result.put("totalCostPrice", totalCostPrice);
        result.put("totalDisplayPrice", totalDisplayPrice);
        return JsonResult.success(result);
    }

    /**
     * 获取兑换券关联的套餐及套餐下的SKU及商品----兑换券管理套餐回显专用
     * @date 2021/7/14 10:16
     * @author caobucao
     * @param exchangeId 兑换券id
     * @return com.dzl.util.JsonResult<java.util.List<com.dzl.exchange.pojo.vo.ExchangeMealGoodsVo>>
     */
    @GetMapping("/getExchangeMealCheckedSkuAndGoods")
    public JsonResult<List<ExchangeMealGoodsVo>> getExchangeMealCheckedSkuAndGoods(Integer exchangeId) {
        return JsonResult.success(service.getExchangeMealCheckedSkuAndGoods(exchangeId));
    }

    /**
     * 添加兑换券商品及SKU
     * @date 2021/7/13 19:53
     * @author caobucao
     * @param dto 兑换券商品对象
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("/addExchangeGoodsAndSku")
    public JsonResult<Map<String, Object>> addExchangeGoodsAndSku(@RequestBody ExchangeGoodsSkuDto dto) {
        if(EmptyUtils.isNotEmpty(dto)) {
            if(EmptyUtils.isEmpty(dto.getExchangeGroupId())) {
                return JsonResult.paramErrWithMsg("未选择兑换券！");
            }
            if (EmptyUtils.isEmpty(dto.getSkuGoodsList())) {
                return JsonResult.paramErrWithMsg("未选择商品！");
            }
            if(dto.getRuleType() == 1) {
                if(dto.getBuyLimit() > dto.getCheckedTotal()) {
                    return JsonResult.paramErrWithMsg("可兑换商品数量，不能大于添加的商品总数量！");
                }
            } else {
                if(dto.getBuyLimit() > dto.getCheckedTotal()) {
                    return JsonResult.paramErrWithMsg("可兑换套餐数量，不能大于添加的套餐总数量！");
                }
            }
            if(dto.getBuyLimit() < 1) {
                return JsonResult.paramErrWithMsg("设置最少兑换数不得小于1！");
            }
            WelfareExchange welfareExchange = new WelfareExchange();
            welfareExchange.setUpdaterName(getAdminInfo().getUserName());
            welfareExchange.setUpdater(getAdminInfo().getId());
            welfareExchange.setUpdateTime(new Date());
            welfareExchange.setId(dto.getExchangeGroupId());
            welfareExchange.setRuleType(dto.getRuleType());
            welfareExchange.setBuyLimit(dto.getBuyLimit());
            welfareExchange.setIsSaved(1); //代表保存过
            return JsonResult.success(welfareExchangeGoodsService.addExchangeGoodsSku(welfareExchange, dto));
        }
        return JsonResult.paramErrWithMsg("测试脏数据错误！");
    }

    /**
     * 保存兑换券套餐
     * @date 2021/7/10 17:40
     * @author caobucao
     * @param dto 传输类
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("/addMealGoodsAndSku")
    public JsonResult<Map<String, Object>> addMealGoodsAndSku(@RequestBody ExchangeMealGoodsDto dto) {
        if(EmptyUtils.isEmpty(dto.getExchangeGroupId())) {
            return JsonResult.paramErrWithMsg("请传入兑换券组id");
        }
        if(EmptyUtils.isEmpty(dto.getMealList())) {
            return JsonResult.paramErrWithMsg("请添加套餐！");
        }
        if(dto.getRuleType() == 1) {
            if(dto.getBuyLimit() > dto.getCheckedTotal()) {
                return JsonResult.paramErrWithMsg("可兑换商品数量，不能大于添加的商品总数量！");
            }
        } else {
            if(dto.getBuyLimit() > dto.getCheckedTotal()) {
                return JsonResult.paramErrWithMsg("可兑换套餐数量，不能大于添加的套餐总数量！");
            }
        }
        //判断是否有重复的套餐名字
        List<String> mealNameList = dto.getMealList().stream().map(MealGoodsSkuListDto::getMealName).collect(Collectors.toList());
        long count = mealNameList.stream().distinct().count();
        if(mealNameList.size() != count) {
            return JsonResult.paramErrWithMsg("存在重复的套餐名称，请更改后重试！");
        }
        WelfareExchange welfareExchange = new WelfareExchange();
        welfareExchange.setUpdaterName(getAdminInfo().getUserName());
        welfareExchange.setUpdateTime(new Date());
        welfareExchange.setId(dto.getExchangeGroupId());
        welfareExchange.setRuleType(dto.getRuleType());
        welfareExchange.setBuyLimit(dto.getBuyLimit());
        welfareExchange.setIsSaved(1);
        welfareExchangeService.updateByPrimaryKeySelective(welfareExchange);
        return JsonResult.success(service.addMealGoodsAndSku(dto));
    }

    /**
     * 修改兑换券商品展示价
     * @param jsonObject type 1兑换券商品 2兑换券套餐商品
     * @param jsonObject exchangeGoodsId 兑换券商品表主键id
     * @param jsonObject displayPrice 兑换券商品展示价格
     * @author liuguanjun
     * @date 2021/12/06 11:21
     */
    @PostMapping("updateExchangeGoodsDisplayPrice")
    public JsonResult<Integer> updateExchangeGoodsDisplayPrice(@RequestBody JSONObject jsonObject) {
        Integer type = jsonObject.getInteger("type");
        Integer exchangeGoodsId = jsonObject.getInteger("exchangeGoodsId");
        BigDecimal displayPrice = jsonObject.getBigDecimal("displayPrice");
        if(EmptyUtils.isEmpty(type)) {
            return JsonResult.paramErrWithMsg("请传入type");
        }
        if(EmptyUtils.isEmpty(exchangeGoodsId)) {
            return JsonResult.paramErrWithMsg("请传入exchangeGoodsId");
        }
        if(EmptyUtils.isEmpty(displayPrice)) {
            return JsonResult.paramErrWithMsg("请传入displayPrice");
        }
        return JsonResult.success(service.updateExchangeGoodsDisplayPrice(type,exchangeGoodsId,displayPrice));
    }

    /**
     * 修改兑换券备注
     * @date 2021/7/20 10:45
     * @author caobucao
     * @param jsonObject 入参 id及备注
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("updateExchangeRemark")
    public JsonResult<Integer> updateCardRemark(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        String remark = jsonObject.getString("remark");
        if(EmptyUtils.isEmpty(id)) {
            return JsonResult.paramErrWithMsg("请传入id");
        }
        WelfareExchange welfareExchange = new WelfareExchange();
        welfareExchange.setId(id);
        welfareExchange.setRemark(remark);
        welfareExchange.setUpdateTime(new Date());
        welfareExchange.setUpdaterName(getAdminInfo().getUserName());
        welfareExchange.setUpdater(getAdminInfo().getId());
        return JsonResult.success(service.updateByPrimaryKeySelective(welfareExchange));
    }

    /**
     * 修改兑换券名称
     * @date 2021/7/20 10:45
     * @author caobucao
     * @param jsonObject 入参 id及名称
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("updateExchangeName")
    public JsonResult<Integer> updateExchangeName(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        String name = jsonObject.getString("name");
        if(EmptyUtils.isEmpty(id)) {
            return JsonResult.paramErrWithMsg("请传入id");
        }
        if(EmptyUtils.isEmpty(name)) {
            return JsonResult.paramErrWithMsg("请输入名称！");
        }
        WelfareExchange welfareExchange = new WelfareExchange();
        welfareExchange.setId(id);
        welfareExchange.setName(name);
        welfareExchange.setUpdateTime(new Date());
        welfareExchange.setUpdaterName(getAdminInfo().getUserName());
        welfareExchange.setUpdater(getAdminInfo().getId());
        return JsonResult.success(service.updateByPrimaryKeySelective(welfareExchange));
    }

}
